#ifndef RESULT_LIB_H_
#define RESULT_LIB_H_

#include <cstring>
#include <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <sstream>

#include "Student.h"
#include "Student_lib.h"
#include "Subject.h"
#include "Subject_lib.h"
#include "result.h"

using namespace std;

void Add_result(string s, Result l[], int &numberResult){
    string temp, a_sid;
    int a_stu_id, a_m_score, a_f_score;

    int mark = s.find(":");
    a_stu_id = atoi(s.substr(0,mark).c_str());

    temp = s.substr(mark+1);
    mark = temp.find(":");
    a_sid = temp.substr(0,mark);

    temp = temp.substr(mark+1);
    mark = temp.find(":");
    a_m_score = atoi(temp.substr(0,mark).c_str());

    temp = temp.substr(mark+1);
    mark = temp.find(";");
    a_f_score = atoi(temp.substr(0,mark).c_str());

    Result result(a_stu_id, a_sid, a_m_score, a_f_score);
    l[numberResult] = result;
    numberResult++;
}

void Read_result(string _file, Result l[], int &numberResult){
    ifstream fin;
    fin.open(_file.c_str());
    if(!fin.is_open()){
        cout<<"Cannot open file.\n";
        exit(1);
    }else{
        string s = "";
        while (getline(fin, s)){
            Add_result(s, l, numberResult);
        }
        fin.close();
    }
}

void Get_student_results(int stu_id, Result l[], int numberResult, Result result[], int &numberResultOut){
    int i = 0;

    for (i = 0; i < numberResult; i++){
        if (l[i].Get_stu_id() == stu_id){
            result[numberResultOut] = l[i];
            numberResultOut++;
        }
    }
}

void Get_subject_results(string sid, Result l[], int numberResult, Result result[], int &numberResultOut){
    int i = 0;

    for (i = 0; i < numberResult; i++){
        if (l[i].Get_s_id() == sid){
            result[numberResultOut] = l[i];
            numberResultOut++;
        }
    }
}

void Show_result(Result result){
    int i, j;
    Student stu[100];
    Subject sub[100];

    i = 0;
    Read_student("Student.txt", stu, i);
    Student _stu = Get_student_by_id(result.Get_stu_id(), stu, i);

    j = 0;
    Read_subject("Subject.txt", sub, j);
    Subject _sub = Get_subject_by_id(result.Get_s_id(), sub, j);

    short _percent = _sub.Get_percent_midterm();
    int _midterm = result.Get_midterm();
    int _final = result.Get_final();

    int _av = (_midterm * _percent + _final * (100 - _percent))/100;
    string _fp;

    if ((_av < 10) || (_final <= 4)){
        _fp = "F";
    }else{
        _fp = "P";
    }

    ostringstream ss;
    ss << _stu.Get_fname() << "\t" << _sub.Get_sname() << "\t" << _midterm << "\t" << _final << "\t" << _av << "\t" << _fp << "\n";
    cout << ss.str();
}



#endif
